const { classApi } = require('../../../utils/api');

Page({
  data: {
    classes: [],
    filteredClasses: [],
    loading: false,
    error: null,
    searchKeyword: '',
    currentFilter: 'all',
    currentUserId: 1 // 这里应该从用户登录信息中获取
  },

  onLoad() {
    this.loadClasses();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadClasses();
  },

  // 加载班级列表
  async loadClasses() {
    this.setData({ loading: true, error: null });
    
    try {
      const classes = await classApi.getAllClasses();
      console.log('获取班级列表成功:', classes);
      
      // 处理班级数据，添加格式化时间等
      const processedClasses = classes.map(classItem => ({
        ...classItem,
        formattedTime: this.formatTime(classItem.createTime)
      }));
      
      this.setData({ 
        classes: processedClasses,
        filteredClasses: processedClasses,
        loading: false 
      });
      
      // 应用当前筛选
      this.applyFilter();
    } catch (error) {
      console.error('获取班级列表失败:', error);
      this.setData({ 
        error: '加载失败，请重试',
        loading: false 
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前';
    }
    // 小于7天
    if (diff < 604800000) {
      return Math.floor(diff / 86400000) + '天前';
    }
    
    // 超过7天显示具体日期
    return date.toLocaleDateString();
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.applyFilter();
  },

  // 清除搜索
  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.applyFilter();
  },

  // 筛选切换
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    const { classes, searchKeyword, currentFilter } = this.data;
    let filtered = [...classes];

    // 搜索筛选
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(classItem => 
        classItem.className.toLowerCase().includes(keyword) ||
        classItem.grade.toLowerCase().includes(keyword) ||
        classItem.subject.toLowerCase().includes(keyword)
      );
    }

    // 类型筛选
    if (currentFilter === 'my') {
      filtered = filtered.filter(classItem => classItem.creatorUserId === this.data.currentUserId);
    } else if (currentFilter === 'headteacher') {
      filtered = filtered.filter(classItem => classItem.isHeadteacher === 1);
    }

    // 按时间排序
    filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));

    this.setData({ filteredClasses: filtered });
  },

  // 点击班级项
  onClassTap(e) {
    const { classItem } = e.currentTarget.dataset;
    console.log('点击班级:', classItem);
    
    // 显示班级详情
    wx.showModal({
      title: classItem.className,
      content: `年级：${classItem.grade}\n科目：${classItem.subject}\n邀请码：${classItem.classCode}`,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 创建班级
  createClass() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 编辑班级
  editClass(e) {
    const { classItem } = e.currentTarget.dataset;
    console.log('编辑班级:', classItem);
    
    wx.showModal({
      title: '编辑班级',
      content: '编辑功能开发中',
      showCancel: false
    });
  },

  // 删除班级
  deleteClass(e) {
    const { classItem } = e.currentTarget.dataset;
    console.log('删除班级:', classItem);
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个班级吗？',
      success: (res) => {
        if (res.confirm) {
          this.confirmDelete(classItem);
        }
      }
    });
  },

  // 确认删除
  async confirmDelete(classItem) {
    try {
      const result = await classApi.deleteClass(classItem.classId);
      if (result.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        // 重新加载数据
        this.loadClasses();
      } else {
        wx.showToast({
          title: result.message || '删除失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('删除班级失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadClasses().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});
